import React, { FC } from 'react';
import {
  FormPanel,
  FormPanelType,
  InputType,
  type FormPanelObject,
  FormPanelStatus,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  Utils,
} from 'lfun-bg-comp';
import { Breadcrumb, Modal, Tabs, message, Button } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { KG_LEVEL, SCHOOL_ORG_TYPE } from '@/constant/schoolOptions';
import { PageContainer } from '@/component/page-container';
import styles from './index.less';
import EditSchoolInfo from './editSchoolInfo';
import Logs from './logs';
import PlanningSchool from '@/view/unit/planning/editSchoolInfo';
import NameIcon from '@/view/component/nameIcon';
import { SchoolKeyInfo, getSchool, updateSchoolKeyInfo } from '@/service/unit/school';
import utils, { buildPageItemTxtByEduType, getPathRoot } from '@/utils';
import { getPlanningSchool } from '@/service/unit/planning';
import { searchPlanningSchoolOptions } from '@/service/options';
import useCountry from '@/hooks/useCountry';

// eslint-disable-next-line react/require-default-props
const Groups: FC<{ isEdit?: boolean; buttonList?: any[] }> = ({ isEdit = true, buttonList = [] }) => {
  const navigate = useNavigate();
  const { id } = useParams();
  const location = useLocation();
  const [value, setValue] = React.useState<any>({});
  const [editValue, setEditValue] = React.useState({});
  const [showModel, setShowModel] = React.useState(false);
  const [schoolInfoValue, setSchoolInfoValue] = React.useState();
  const [planningSchoolValue, setPlanningSchoolValue] = React.useState();
  const [showLogs, setShowLogs] = React.useState(false);
  const country = useCountry();


  const keyInfo: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
      span: 4,
      inputs: [
        {
          label: '',
          name: 'school_name',
          key: 'school_name',
          required: false,
          ruleType: 'default',
          span: 24,
          inputType: InputType.children,
          props: {
            className: 'allow-edit',
          },
          children: (
            <NameIcon
              span={24}
              isEdit={isEdit}
              onClick={() => {
                setEditValue({ ...value });
                setShowModel(true);
              }}
            />
          ),
        },
        {
          label: buildPageItemTxtByEduType('园所名称(规划口径)'),//Utils.getProps('edu_type') === 'kg' ? '总园' : '规划校',
          name: 'planning_school_id',
          key: 'planning_school_id',
          required: true,
          inputType: InputType.search,
          span: Utils.getProps('edu_type') !== 'kg' ? 5 : 4,
          renderOption: searchPlanningSchoolOptions,
          formatSubmitValue: val => {
            if (typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: buildPageItemTxtByEduType('机构编码'),
          name: 'school_no',
          key: 'school_no',
          span: Utils.getProps('edu_type') !== 'kg' ? 5 : 4,
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
          span: Utils.getProps('edu_type') !== 'kg' ? 5 : 4,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
          span: Utils.getProps('edu_type') !== 'kg' ? 5 : 4,
        },
        {
          label: '星级',
          name: 'school_level',
          key: 'school_level',
          inputType: InputType.select,
          renderOption: KG_LEVEL,
          span: 4,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
        {
          label: '学校办别',
          name: 'school_org_type',
          key: 'school_org_type',
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
          span: 4,
        },
      ],
    },
  ];

  const keyInfoEdit: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 24,
      disabled: true,
      inputs: [
        {
          label: buildPageItemTxtByEduType('园所名称(规划口径)'),
          name: 'planning_school_id',
          key: 'planning_school_id',
          required: true,
          inputType: InputType.search,
          renderOption: searchPlanningSchoolOptions,
          formatSubmitValue: val => {
            if (typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: buildPageItemTxtByEduType('园所名称'),
          name: 'school_name',
          key: 'school_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: buildPageItemTxtByEduType('机构编码'),
          name: 'school_no',
          key: 'school_no',
          required: true,
          disabled: true,
        },
        {
          label: '行政管辖区',
          name: 'borough',
          key: 'borough',
          required: true,
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '地域管辖区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '星级',
          name: 'school_level',
          key: 'school_level',
          inputType: InputType.select,
          renderOption: KG_LEVEL,
          hidden: Utils.getProps('edu_type') !== 'kg',
        },
        {
          label: '学校办别',
          name: 'school_org_type',
          key: 'school_org_type',
          required: true,
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
        },
      ],
    },
  ];
  React.useEffect(() => {
    init();
  }, []);

  const init = async () => {
    utils.showLoading();
    const res = await getSchool(id || location.state.id);
    if (res.success) {
      const resdata: any = utils.flattenObject(res.data);
      if (resdata['school.founder_type']) {
        resdata['school.founder_type'] = [
          resdata['school.founder_type'],
          resdata['school.founder_type_lv2'],
          resdata['school.founder_type_lv2'],
        ];
      }
      if (resdata['school.school_operation_type']) {
        resdata['school.school_operation_type'] = [
          resdata['school.school_operation_type'],
          resdata['school.school_operation_type_lv2'],
          resdata['school.school_operation_type_lv3'],
        ];
      }
      if (!resdata['school_communication.related_license_upload']) {
        delete resdata['school_communication.related_license_upload'];
      }
      resdata['school.urban_rural_nature'] = (resdata['school.urban_rural_nature'] || "").split(',');
      setValue(res.data.school_keyinfo);
      setSchoolInfoValue(resdata);
    } else {
      message.error(res.message);
    }
    utils.hideLoaing(res.success);
  };
  return (
    <PageContainer
      header={
        <Breadcrumb
          items={[
            {
              title: (
                <div className={styles.back}>
                  <LeftOutlined />
                  {buildPageItemTxtByEduType(`园所信息管理（分${Utils.getProps('edu_type') === 'kg' ? '园' : '校'}）`)}
                </div>
              ),
              onClick: () => navigate(`${getPathRoot()}/school`),
            },
          ]}
        />
      }
    >
      <div className={styles.edit_container}>
        <FormPanel
          template={keyInfo}
          key={1}
          buttonsDisplay={false}
          values={value}
          formStatus={FormPanelStatus.nonEdit}
        />
      </div>
      <Button
        style={{
          position: 'absolute',
          top: '80px',
          zIndex: '999',
          right: '50px',
        }}
        type="primary"
        onClick={() => setShowLogs(true)}
      >
        变更日志
      </Button>
      <Logs show={showLogs} onClose={() => setShowLogs(false)} title={value?.school_name} />
      <Tabs
        className={styles.edit_tabs}
        onChange={async key => {
          if (key === '2') {
            const res = await getPlanningSchool(value?.planning_school_id || location?.state?.planning_school_id);
            if (res.success) {
              const resdata: any = utils.flattenObject(res.data);
              if (resdata['planning_school.founder_type']) {
                resdata['planning_school.founder_type'] = [
                  resdata['planning_school.founder_type'],
                  resdata['planning_school.founder_type_lv2'],
                  resdata['planning_school.founder_type_lv2'],
                ];
              }
              if (resdata['planning_school.planning_school_operation_type']) {
                resdata['planning_school.planning_school_operation_type'] = [
                  resdata['planning_school.planning_school_operation_type'],
                  resdata['planning_school.planning_school_operation_type_lv2'],
                  resdata['planning_school.planning_school_operation_type_lv3'],
                ];
              }
              //setValue(res.data.school_keyinfo);
              setPlanningSchoolValue(resdata);
            } else {
              message.error(res.message);
            }
          }
        }}
        type="card"
        items={[
          {
            label: buildPageItemTxtByEduType(Utils.getProps('edu_type') === 'kg' ? '分园基本信息' : '园所基本信息'),
            key: '1',
            children: (
              <div className={`${styles.edit_baisc_info} ${isEdit ? 'submit-block' : 'submit-none'}`}>
                <EditSchoolInfo buttons={buttonList} value={schoolInfoValue} isEdit={isEdit} />
              </div>
            ),
          },
          {
            label: Utils.getProps('edu_type') === 'kg' ? '总园信息' : '学校信息',
            key: '2',
            children: (
              <div className={styles.edit_baisc_info}>
                <PlanningSchool isEdit={false} value={planningSchoolValue} />
              </div>
            ),
          },
          // {
          //   label: '变更日志',
          //   key: '3',
          //   children: <Logs operation_target_type="school" />,
          // },
        ]}
      />
      <Modal title="关键信息编辑" footer={[]} open={showModel} onCancel={() => setShowModel(false)}>
        <FormPanel
          template={keyInfoEdit}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          values={editValue}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const keyInfo: SchoolKeyInfo = { id: location.state.id, ...values };
            if (keyInfo.school_operation_type) {
              keyInfo.school_operation_type_lv2 = keyInfo.school_operation_type[1];
              keyInfo.school_operation_type_lv3 = keyInfo.school_operation_type[2];
              keyInfo.school_operation_type = keyInfo.school_operation_type[0];
            }
            const res = await updateSchoolKeyInfo(keyInfo);
            if (res.success) {
              message.info('修改成功,等待审核');
              formPanelObject.resetFields();
              setShowModel(false);
              init();
            } else {
              formPanelObject.reVaildation(res);
            }
            return false;
          }}
          onReset={() => setShowModel(false)}
        />
      </Modal>
    </PageContainer>
  );
};

export default Groups;
